package com.pms.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.pms.controller.BaseController;
import com.pms.entity.IotWaterPumpGroup;
import com.pms.entity.IotWaterPumpGroupAttr;
import com.pms.entity.UserInfo;
import com.pms.exception.R;
import com.pms.rpc.SystemRpcService;
import com.pms.service.*;
import com.pms.util.DateUtil;
import com.pms.validator.Assert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;

/**
 * <p>
 * 二供模块 数据监测 接口 前端控制器
 * </p>
 *
 * @author asus
 * @since 2018-07-17
 */
@RestController
@RequestMapping("/iot/dataAnalysis")
@Api(value="二供模块 数据分析 接口" ,description = "二供模块 数据分析 接口")
public class IotDataAnalysisController extends BaseController {
    @Autowired
    IIotAgencyService orgService;
    @Autowired
    IIotWaterPumpGroupService waterPumpGroupService;
    @Autowired
    IIotWaterPumpGroupAttrService waterPumpGroupAttrService;
    @Autowired
    SystemRpcService systemRpcService;
    @Autowired
    IGroupIotAgencyService groupIotAgencyService;
    @Autowired
    IWoGiaWpAttrService woGiaWpAttrService;
    /*
    * 实时数据信息
    * @param
    * @return
    */
    @ApiOperation(value = "查询数据分析报表")
    @RequestMapping(value = "/readDataAnalysisReportForm",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="searchValue",value="搜索框内容",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="pageSize",value="分页查询条数,默认10条",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="pageNum",value="分页查询页数",required = false,dataType = "int",paramType="form"),
    })
    public R readDataAnalysisReportForm(String waterPumpGroupIds,String startTime,String endTime,String searchValue,Integer pageSize,Integer pageNum){
       Assert.parameterIsBlank(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
       Assert.parameterIsBlank(startTime,"起始时间不能为空");
       Assert.parameterIsBlank(startTime,"截止时间不能为空");
        if(pageNum==null||pageNum < 1){pageNum=1;}
        if(pageSize==null||pageSize < 1){pageSize=10;}
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Page<Map<String,Object>> pages = new Page<Map<String,Object>>(pageNum,pageSize);
        // 获取当前用户角色
        Map<String,String> currentUserMap=getCurrentUserMap();
        UserInfo currentUserInfo=systemRpcService.getUserByUsername(currentUserMap.get("userName"),currentUserMap.get("companyCode"));
        Assert.isNull(currentUserInfo,"请重新登录");
        Assert.isNull(currentUserInfo.getGroupType(),"请重新登录");
        List<Long> roleWaterPumpGroupIdList = null;
//        String roleWaterPumpGroupIds = null;
        if(1!=currentUserInfo.getGroupType()){// 自定义角色
            // 获取角色拥有的 机构id
            String roleAgencyIdsStr =groupIotAgencyService.getAgencyIdsStrByGroupId(currentUserInfo.getGroupId()+"");
            Assert.parameterIsBlank(roleAgencyIdsStr,"您暂无机构权限，请联系管理员");
//           roleWaterPumpGroupIds = waterPumpGroupService.getGroupIdsStrByHouseId(roleAgencyIdsStr);
            roleWaterPumpGroupIdList = waterPumpGroupService.getGroupIdListByHouseId(roleAgencyIdsStr);
            if(roleWaterPumpGroupIdList==null||roleWaterPumpGroupIdList.isEmpty()){// 未查询到 水泵组 直接返回空数据
                pages.setRecords(null);
                return R.ok().put("data",pages);
            }
        }
       if(!waterPumpGroupIds.equals("-1")){// 查询全部 - 系统级别
           List<Long> PumpGroupIdList = new ArrayList<Long>();
           StringTokenizer strTokenizer=new StringTokenizer(waterPumpGroupIds,",");
           try {
               while (strTokenizer.hasMoreElements()) {
                   PumpGroupIdList.add(Long.parseLong(strTokenizer.nextToken()));
               }
           }catch (NumberFormatException ex){
               return R.error(400,"参数水泵组id格式错误");
           }
           if(roleWaterPumpGroupIdList!=null){
               roleWaterPumpGroupIdList.retainAll(PumpGroupIdList);// 取交集
           }
           if(roleWaterPumpGroupIdList==null){
               roleWaterPumpGroupIdList=PumpGroupIdList;//直接赋值
           }
       }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        Wrapper<Map<String,Object>> wr = new EntityWrapper<Map<String,Object>>();
        wr.eq("group1.company_code",currentUserMap.get("companyCode"));
        if(roleWaterPumpGroupIdList!=null && !roleWaterPumpGroupIdList.isEmpty() ){
            wr.in("group1.group_id", roleWaterPumpGroupIdList);
        }
        if(StringUtils.isNotBlank(searchValue)){// 搜索框内容 根据 水泵房名称和水泵名称 搜索
            wr.andNew(" group1.group_name like '%"+searchValue+"%'");
        }
        pages = waterPumpGroupService.readDataAnalysisReportFormPage(pages,wr,paramMap);
        return R.ok().put("data",pages);
    }
      /*
       * 查询数据分析曲线
       * @param
       * @return
       */
    @ApiOperation(value = "查询数据分析曲线")
    @RequestMapping(value = "/readDataAnalysisCurve",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="monitorParam",value="监测参数(1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)",required = true,dataType = "int",paramType="form"),
    })
    public R readWaterPumpGroupInfoByHouse(String waterPumpGroupIds,String startTime,String endTime,Integer monitorParam){
        Assert.parameterIsNull(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
        Assert.parameterIsBlank(startTime,"起始时间不能为空");
        Assert.parameterIsBlank(startTime,"截止时间不能为空");
        Assert.parameterIsNull(monitorParam,"请选择监控参数");
        String readColumn = getReadColumnName(monitorParam);
        Assert.parameterIsBlank(readColumn,"该监控参数暂无数据");
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("column",readColumn);
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        if(waterPumpGroupIds!=null&&!waterPumpGroupIds.equals("-1")) {
            paramMap.put("waterPumpGroupIds", waterPumpGroupIds);
        }
        paramMap.put("companyCode",getCurrentCompanyCode());
        List<Map<String,Object>> dataList = waterPumpGroupService.readDataAnalysisCurve(paramMap,null);
        if(dataList==null){dataList= new ArrayList<Map<String,Object>>();}
//        Map<String,Object> returnMap = new HashMap<String,Object>();
//        for(int x=0,length = dataList.size();x<length;x++){
//            returnMap.put(dataList.get(x).get("groupName").toString(),dataList.get(x));
//        }
        for(int x=0,lenth=dataList.size();x<lenth;x++){
            List<String> retimeFormatList = (List<String>) dataList.get(x).get("timeArr");
            if(retimeFormatList==null||retimeFormatList.isEmpty()){
                dataList.get(x).put("valueArr",new ArrayList<>());
            }
        }
        return R.ok().put("data",dataList);
    }


    /*
      * 查询设备组历史详情
      * @param
      * @return
      */
    @ApiOperation(value = "查询设备组历史详情")
    @RequestMapping(value = "/readPumpGroupHistory",method ={ RequestMethod.POST})
    @ApiImplicitParams({
         @ApiImplicitParam(name="groupCode",value="设备组编号",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = false,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="pageSize",value="分页查询条数,默认100条",required = false,dataType = "int",paramType="form"),
         @ApiImplicitParam(name="pageNum",value="分页查询页数",required = false,dataType = "int",paramType="form"),
   })
    public R readPumpGroupHistory(String groupCode,Integer pageSize,Integer pageNum,String startTime,String endTime){
        Assert.parameterIsBlank(groupCode,"设备组编号groupCode不能为空");
//        Date startDate = DateUtil.stringToDate(startTime);
//        if(startDate==null){
//            return R.error(400,"起始时间格式有误");
//        }
//        Date endDate = DateUtil.stringToDate(endTime);
//        if(endDate==null){
//            return R.error(400,"截止时间格式有误");
//        }
        IotWaterPumpGroup waterPumpGroup = waterPumpGroupService.selectOne(new EntityWrapper<IotWaterPumpGroup>().eq("group_code",groupCode));
        Assert.parameterIsNull(waterPumpGroup,"参数groupCode错误");
        if(pageSize==null||pageSize<1){pageSize = 100;}
        if(pageSize>3000){pageSize = 3000;}
        if(pageNum==null||pageNum<1){pageNum = 1;}
        Page<Map<String,Object>> pages = new Page<Map<String,Object>>(pageNum,pageSize);
        pages.setSearchCount(false);
        Integer Total = null;
        if(waterPumpGroup.getDataSource()==null){
            waterPumpGroup.setDataSource(1);
        }
        if(waterPumpGroup.getDataSource()==1) {
            Wrapper<IotWaterPumpGroupAttr> countWr = new EntityWrapper<IotWaterPumpGroupAttr>();
            countWr.eq("deviceName", groupCode);
            Total = waterPumpGroupAttrService.selectCount(countWr);
        }
        if(waterPumpGroup.getDataSource()==2) {
            Total = woGiaWpAttrService.selectCountTableDataNum("`"+groupCode.substring(0,groupCode.indexOf("|"))+"`");
        }
        if (Total > 3000) {
            Total = 3000;
        }
        pages.setTotal(Total);//最多查询3000条
        Map<String,Object> sqlmap = new HashMap<String,Object>();
        sqlmap.put("deviceName",groupCode);
        sqlmap.put("deviceDataSource",waterPumpGroup.getDataSource());
        pages =waterPumpGroupAttrService.readPumpGroupHistory(pages,sqlmap);
        return R.ok().put("data",pages);
    }


    /*
     * 查询数据分析曲线
     * @param
     * @return
     */
    @ApiOperation(value = "查询数据分析曲线-新接口(共用同一个时间轴)")
    @RequestMapping(value = "/readDataAnalysisCurve_new",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="monitorParam",value="监测参数(1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="dataIsZero",value="是否null值补0（1-是）",required = false,dataType = "int",paramType="form"),
    })
    public R readDataAnalysisCurve_new(String waterPumpGroupIds,String startTime,String endTime,Integer monitorParam,Integer dataIsZero){
        Assert.parameterIsNull(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
        Assert.parameterIsBlank(startTime,"起始时间不能为空");
        Assert.parameterIsBlank(startTime,"截止时间不能为空");
        Assert.parameterIsNull(monitorParam,"请选择监控参数");
        String readColumn = getReadColumnName(monitorParam);
        Assert.parameterIsBlank(readColumn,"该监控参数暂无数据");
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("column",readColumn);
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        if(waterPumpGroupIds!=null&&!waterPumpGroupIds.equals("-1")){
            paramMap.put("waterPumpGroupIds",waterPumpGroupIds);
        }
        paramMap.put("companyCode",getCurrentCompanyCode());
        Map<String,Object> dataList =null;
        if(dataIsZero==null||dataIsZero!=1){
            dataList = waterPumpGroupService.readDataAnalysisCurve_New(paramMap);
        }
        if(dataIsZero==1){
            dataList = waterPumpGroupService.readDataAnalysisCurve_New(paramMap,getReadColumnvalueType(monitorParam));
        }
        return R.ok().put("data",dataList);
    }

    /*
        * 查询数据分析曲线
        * @param
        * @return
        */
    @ApiOperation(value = "查询数据分析曲线-新接口(多组x轴对多组y轴)")
    @RequestMapping(value = "/readDataAnalysisCurve_new_xToy",method ={ RequestMethod.POST})
    @ApiImplicitParams({
            @ApiImplicitParam(name="waterPumpGroupIds",value="左侧机构栏勾选的所有水泵组id字符串以,分割",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="startTime",value="起始时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="endTime",value="截止时间(YYYY-DD-MM HH:mm:ss)",required = true,dataType = "String",paramType="form"),
            @ApiImplicitParam(name="monitorParam",value="监测参数(1-电流,2-电压,3-进水压力,4-出水压力,5-进水瞬时流量,6-出水瞬时流量)",required = true,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="dataIsZero",value="数据是否null值补0(该参数不传)",required = false,dataType = "int",paramType="form"),
            @ApiImplicitParam(name="companyCode",value="公司编码",required = false,dataType = "String",paramType="form"),
    })
    public R readDataAnalysisCurve_new_xToy(String waterPumpGroupIds,String startTime,String endTime,Integer monitorParam,Integer dataIsZero,String companyCode){
        Assert.parameterIsNull(waterPumpGroupIds,"参数waterPumpGroupIds不能为空");
        Assert.parameterIsBlank(startTime,"起始时间不能为空");
        Assert.parameterIsBlank(startTime,"截止时间不能为空");
        Assert.parameterIsNull(monitorParam,"请选择监控参数");
        String readColumn = getReadColumnName(monitorParam);
        Assert.parameterIsBlank(readColumn,"该监控参数暂无数据");
        Date startDate = DateUtil.stringToDate(startTime);
        if(startDate==null){
            return R.error(400,"起始时间格式有误");
        }
        Date endDate = DateUtil.stringToDate(endTime);
        if(endDate==null){
            return R.error(400,"截止时间格式有误");
        }
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("column",readColumn);
        paramMap.put("startTime",startDate);
        paramMap.put("endTime",endDate);
        paramMap.put("monitorParam",monitorParam);
        if(waterPumpGroupIds!=null&&!waterPumpGroupIds.equals("-1")){
            paramMap.put("waterPumpGroupIds",waterPumpGroupIds);
        }
        if(StringUtils.isBlank(companyCode)){
            companyCode = getCurrentCompanyCode();
        }
        paramMap.put("companyCode",companyCode);
        List<Map<String,Object>>  dataList = waterPumpGroupService.readDataAnalysisCurve(paramMap,3);
        return R.ok().put("data",dataList);
    }
    private static String getReadColumnName(Integer monitorParam){
        if(monitorParam==null){return null;}
        switch (monitorParam){
            case 1: return null;// 电流
            case 2: return null;// 电压
            case 3: return "FORMAT(IFNULL(attr.SZGWYL,0.0),2) as value_";// 进水压力
            case 4: return "FORMAT(IFNULL(attr.pressureFeedback,0.0),2) as value_";// 出水压力
            case 5: return null;// 进水瞬时流量
            case 6: return null;// 出水瞬时流量
            default: return null;
        }
    }


    private static int getReadColumnvalueType(Integer monitorParam){
        int valueType = 2;// 默认 double 类型
        if(monitorParam==null){return valueType;}
        switch (monitorParam){
            case 1: ;// 电流
            case 2: ;// 电压
            case 3: valueType = 2;// 进水压力
            case 4: valueType = 2;// 出水压力
            case 5: ;// 进水瞬时流量
            case 6: ;// 出水瞬时流量
            default: valueType = 2;
        }
        return valueType;
    }



}
